package model

import (
	"database/sql"
	"fmt"
	sq "github.com/Masterminds/squirrel"
	"strings"

	"github.com/zeromicro/go-zero/core/stores/builder"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"github.com/zeromicro/go-zero/core/stringx"
)

var (
	provinceFieldNames          = builder.RawFieldNames(&Province{}, true)
	provinceRows                = strings.Join(provinceFieldNames, ",")
	provinceRowsExpectAutoSet   = strings.Join(stringx.Remove(provinceFieldNames, "create_time", "update_time"), ",")
	provinceRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(provinceFieldNames, "id", "create_time", "update_time"))

	cachePublicProvinceIdPrefix   = "cache:public:province:id:"
	cachePublicProvinceCodePrefix = "cache:public:province:code:"
)

type (
	ProvinceModel interface {
		Insert(data *Province) (sql.Result, error)
		FindOne(id int64) (*Province, error)
		Update(data *Province) error
		Delete(id int64) error
		provinceCustomModel
	}
	provinceCustomModel interface {
		FindOneByCode(code string) (*Province, error)
		FindList() ([]Province, error)
	}
	defaultProvinceModel struct {
		sqlc.CachedConn
		table string
	}

	Province struct {
		Id         int64  `db:"id"`
		Name       string `db:"name"`
		ProvinceId string `db:"province_id"`
	}
)

func NewProvinceModel(conn sqlx.SqlConn, c cache.CacheConf) ProvinceModel {
	return &defaultProvinceModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      `"public"."province"`,
	}
}

func (m *defaultProvinceModel) Insert(data *Province) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3)", m.table, provinceRowsExpectAutoSet)
	ret, err := m.ExecNoCache(query, data.Id, data.Name, data.ProvinceId)

	return ret, err
}

func (m *defaultProvinceModel) FindOne(id int64) (*Province, error) {
	publicProvinceIdKey := fmt.Sprintf("%s%v", cachePublicProvinceIdPrefix, id)
	var resp Province
	err := m.QueryRow(&resp, publicProvinceIdKey, func(conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where id = $1 limit 1", provinceRows, m.table)
		return conn.QueryRow(v, query, id)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
func (m *defaultProvinceModel) FindOneByCode(code string) (*Province, error) {
	publicProvinceCodeKey := fmt.Sprintf("%s%v", cachePublicProvinceCodePrefix, code)
	var resp Province
	err := m.QueryRow(&resp, publicProvinceCodeKey, func(conn sqlx.SqlConn, v interface{}) error {
		query, args, err := sq.Select(provinceRows).From(m.table).Where(sq.Eq{"province_id": code}).Limit(1).PlaceholderFormat(sq.Dollar).ToSql()
		if err != nil {
			return err
		}
		return conn.QueryRow(v, query, args...)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}
func (m *defaultProvinceModel) FindList() ([]Province, error) {

	var resp []Province
	query, args, err := sq.Select(provinceRows).From(m.table).PlaceholderFormat(sq.Dollar).ToSql()
	if err != nil {
		return nil, err
	}
	err = m.QueryRowsNoCache(&resp, query, args...)
	if err != nil {
		return nil, err
	}
	return resp, nil
}
func (m *defaultProvinceModel) Update(data *Province) error {
	publicProvinceIdKey := fmt.Sprintf("%s%v", cachePublicProvinceIdPrefix, data.Id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where id = $1", m.table, provinceRowsWithPlaceHolder)
		return conn.Exec(query, data.Id, data.Name, data.ProvinceId)
	}, publicProvinceIdKey)
	return err
}

func (m *defaultProvinceModel) Delete(id int64) error {

	publicProvinceIdKey := fmt.Sprintf("%s%v", cachePublicProvinceIdPrefix, id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where id = $1", m.table)
		return conn.Exec(query, id)
	}, publicProvinceIdKey)
	return err
}

func (m *defaultProvinceModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cachePublicProvinceIdPrefix, primary)
}

func (m *defaultProvinceModel) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where id = $1 limit 1", provinceRows, m.table)
	return conn.QueryRow(v, query, primary)
}
